/**
*
* @brief	消息格式定义
* @author	yun
* @date		2016-12-21
* @desc		与服务器交换数据格式
* @version  v0.1
*
*/

#include	"app_message.h"

#include	<string.h>
#include	<stdio.h>

#define		MESSAGE_SEND_FORMAT	 	"{\"sev\":\"%s\",\"msg\":%s}\n"

#define		MESSAGE_POST_SEV		"sev"
#define		MESSAGE_POST_DATA		"post"

//
// packet: 发送包缓冲区
// send: 发送消息结构体
//
int message_encode(char * packet, const message_send_t * send){
	if(packet == NULL || send == NULL){
		return -1;
	}
	return sprintf(packet, MESSAGE_SEND_FORMAT, send->type, send->date);
}

//
// post: 数据包解析结构体
// packet: 接收的数据包
// 
int message_post_parse(message_post_t * post, const char * packet){
	if(packet == NULL || post == NULL) {
		return -1;
	}
	
	post->type = NULL;
	post->data = NULL;
	
	// 格式解析
	post->json = cJSON_Parse(packet);
	if(post->json == NULL){
		return -1;
	}
	
	// 解析类型 post_type
	cJSON *post_t = cJSON_GetObjectItem(post->json, MESSAGE_POST_SEV);
	if (post_t == NULL || post_t->type != cJSON_String){
		return -1;
	}
	
	// 解析数据
	cJSON * post_d = cJSON_GetObjectItem(post->json, MESSAGE_POST_DATA);
	if(post_d == NULL || post_d->type != cJSON_Object){
		return -1;
	}
	
	// 汇总处理结果
	post->type = post_t->valuestring;
	post->data = post_d;
	return 0;
}

//
// 当JSON格式的消息内容被转移之后，调用此函数销毁解析消息占用的内存空间
//
int message_post_release(message_post_t * post){
	if(post->json != NULL){
		cJSON_Delete(post->json);
		post->json = NULL;
	}
	post->type = NULL;
	post->data = NULL;
	return 0;
}

#include	"app_conf.h"
#include	"platform_logger.h"
#include	"freeRTOS.h"

//
int message_test(void){
	
	char packet[APP_SERVER_PACKET_LEN_MAX] = { 0 };
	
	char * data = "{\"code\":\"ok\",\"time\":\"2016-12-06 14:48:22\"}";
	message_send_t send;
	send.type = "login";
	send.date = "{\"code\":\"ok\",\"time\":\"2016-12-06 14:48:22\"}";
	
	message_encode(packet, &send);
	
	log_info_printf("send: %s", packet);
	
	char * post = "{\"post\":\"login\",\"data\":{\"code\":\"ok\",\"time\":\"2016-12-06 14:48:22\"}}";
	message_post_t  message_post;
	
	if(message_post_parse(&message_post, post) != -1) {
		log_info_printf("rev: %s", message_post.type);
		char *json = cJSON_PrintUnformatted(message_post.data);
		log_info_printf("rev: %s", json);
		vPortFree(json);
	}
	
	message_post_release(&message_post);
	
	return 0;
}


